package com.sline.Socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Demo2_Received {
    public static void main(String[] args) throws IOException {
        // 创建socket, 相当于创建码头
        DatagramSocket socket = new DatagramSocket(6666);
        // 创建packet, 相当于创建集装箱
        DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

        while (true) {
            // 接收数据
            socket.receive(packet);

            //获取数据
            byte[] arr = packet.getData();
            // 获取有效的字节个数
            int len = packet.getLength();

            String receivedMsg = new String(arr, 0, len);
            String ip = packet.getAddress().getHostAddress();
            int port = packet.getPort();
            System.out.println(ip + ":" + port + " " + receivedMsg);
        }

//        socket.close();

    }
}
